<template>
  <div class="app-container">
    <div class="app-container-content role">
      <!-- 操作区域 -->
      <div class="btn">
        <div class="left">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click.native="handleAdd()">新增</el-button>
          <!-- <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDel()">批量删除</el-button> -->
        </div>
      </div>
      <div ref="tablebox" class="tablebox">
        <el-table :data="tableData" @select="handleSelectList">
          <el-table-column prop="roleCode" label="编码" />
          <el-table-column prop="roleName" label="名称" />
          <el-table-column label="权限">
            <template slot-scope="scope">
              <el-button type="text" @click="handlePermission(scope.row.id)">授权</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="describes" label="描述" />
          <el-table-column label="操作" align="center" width="180px">
            <template slot-scope="scope">
              <el-button type="success" size="mini" @click="handleAdd(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDel([scope.row.id])">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        background
        :page-sizes="[5, 10, 15, 30, 50, 100]"
        :page-size="pageCondition.size"
        layout="total, prev, pager, next, sizes, jumper"
        :total="pageCondition.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 新增弹出窗口 -->
      <el-dialog
        :close-on-click-modal="false"
        :title="dialogType"
        :visible.sync="addDialogShow"
        width="30%"
        :before-close="handleClose"
      >
        <div v-if="addDialogShow" class="dialog-content">
          <el-form ref="roleform" :rules="rule" :model="roleForm" label-width="60px">
            <el-form-item label="编码" prop="roleCode">
              <el-input v-model="roleForm.roleCode" />
            </el-form-item>
            <el-form-item label="名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="roleForm.describes"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入角色描述"
              />
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer">
          <el-button type="primary" @click="onSubmitRole('roleform')">确认</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </el-dialog>

      <!-- 查看窗口 -->
      <el-dialog
        :close-on-click-modal="false"
        title="角色授权"
        :visible.sync="permissionDialogShow"
        width="30%"
        class="editdialog"
        :before-close="handlePermissionClose"
      >
        <el-tree
          ref="permissiontree"
          :data="permissionData"
          node-key="id"
          show-checkbox
          :default-checked-keys="checkedkeys"
          :check-strictly="true"
          :default-expand-all="true"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <el-button v-if="data.permType ===1" size="mini" type="text">菜单权限</el-button>
            <el-button v-if="data.permType ===2" size="mini" type="text" style="color: green">资源权限</el-button>
          </span>
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handlePermissionClose">取 消</el-button>
          <el-button type="primary" @click="onSubmitPermission">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import roleApi from '@/api/system/role'
import permApi from '@/api/system/permission'

export default {
  name: 'Role',
  data() {
    return {
      addDialogShow: false, // 新增弹出框是否显示
      dialogType: '新增',
      roleForm: {},
      tableData: [], // 展现表格的数据
      pageCondition: {
        page: 1,
        size: 15,
        sort: '',
        total: 0
      }, // 分页条件
      permissionDialogShow: false, // 授权弹窗是否显示
      permissionData: [],
      roleId: '', // 所选角色的id
      checkedkeys: [], // 所选角色的权限
      rule: {
        roleCode: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.listPage()
  },
  methods: {
    // 获取角色(分页)
    listPage: function() {
      roleApi.listPage(this.pageCondition).then(res => {
        this.tableData = res.data.content
        this.pageCondition.total = parseInt(res.data.totalElements)
      })
    },
    // 每页显示数量调整
    handleSizeChange(val) {
      this.pageCondition.size = val
      this.listPage()
    },
    // 页面修改
    handleCurrentChange(val) {
      this.pageCondition.page = val
      this.listPage()
    },
    // 新增按钮---编辑
    handleAdd: function(row) {
      this.addr = []
      if (row) {
        this.roleForm = { ...row }
        this.dialogType = '编辑'
      } else {
        this.dialogType = '新增'
      }
      this.addDialogShow = true
    },
    // 新增或修改弹窗内事件
    // 关闭弹窗前执行的事件
    handleClose: function() {
      this.addDialogShow = false
      this.roleForm = {}
    },
    // 点击取消
    handleCancel: function() {
      this.handleClose()
    },
    // 点击确认新增或修改
    onSubmitRole: function(fromName) {
      this.$refs[fromName].validate(valid => {
        if (valid) {
          if (this.dialogType === '新增') {
            roleApi.add(this.roleForm).then(res => {
              if (res.code === 200 && res.msg === 'ok') {
                this.handleClose()
                this.$notify({
                  title: '新增成功',
                  type: 'success'
                })
                this.listPage()
              } else {
                this.$notify.error({
                  title: '新增失败'
                })
              }
            })
          } else {
            roleApi.edit(this.roleForm).then(res => {
              if (res.code === 200 && res.msg === 'ok') {
                this.handleClose()
                this.$notify({
                  title: '修改成功',
                  type: 'success'
                })
                this.listPage()
              } else {
                this.$notify.error({
                  title: '修改失败'
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 多选框事件
    handleSelectList: function(selection, row) {
      this.selectList = selection.map(item => item.id)
    },
    // 删除
    handleDel: function(idList) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (idList) {
            this.selectList = idList
          }
          var params = { ids: this.selectList }
          roleApi.deleteByIds(params).then(res => {
            if (res.code === 200 && res.msg === 'ok') {
              this.$notify({
                title: '删除成功',
                type: 'success'
              })
              this.listPage()
            } else {
              this.$notify.error({
                title: '删除失败'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 权限关闭弹窗事件
    handlePermissionClose: function() {
      this.permissionDialogShow = false
      this.roleId = ''
    },
    // 点击授权按钮
    handlePermission: function(id) {
      permApi.permTree().then(res => {
        this.permissionData = res.data
      })
      this.roleId = id
      this.checkedkeys = []
      this.permissionDialogShow = true
      roleApi.getPerms(this.roleId).then(res => {
        this.checkedkeys = res.data.map(item => item.id)
      })
    },
    // 提交授权
    onSubmitPermission: function() {
      var params = {
        roleId: this.roleId,
        permIds: [
          ...this.$refs.permissiontree.getCheckedKeys()
        ]
      }
      roleApi.authorize(params).then(res => {
        if (res.code === 200 && res.msg === 'ok') {
          this.handleClose()
          this.$notify({
            title: '授权成功',
            type: 'success'
          })
          this.listPage()
          this.handlePermissionClose()
        } else {
          this.$notify.error({
            title: '授权失败'
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
<style lang="scss" scoped>
.app-container {
  .role {
    background: #fff;
    height: 100%;
    overflow: hidden;

    .btn {
      padding: 0 0 16px 0;
      height: 52px;
    }

    .tablebox {
      overflow: auto;
      margin-bottom: 16px;
    }

    .el-select {
      width: 100%;
    }
  }
}
</style>
